package com.ding.custommanagersys.controller;

import com.ding.custommanagersys.entity.ResultData;
import com.ding.custommanagersys.entity.User;
import com.ding.custommanagersys.service.IUserService;
import com.ramostear.captcha.HappyCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ding
 * @since 2023-04-18
 */
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    //用户登录
    @PostMapping("user/login")
    public ResultData<Integer> getLogin(User user, HttpServletRequest request,
                                        @RequestParam("captcha") String captcha){
        ResultData<Integer> resp = new ResultData<>();
        //判断验证码是否正确
        boolean flag = HappyCaptcha.verification(request,captcha,true);
        if(flag){
            User loginUser = userService.userLogin(user.gettUsername(), user.gettPassword());
            if(loginUser == null){
                resp.error("账号不存在或密码错误");
            }else{
                HttpSession session = request.getSession();
                session.setAttribute("user",loginUser);
                resp.ok();
            }
        }else{
            resp.error("验证码错误");
        }
        return resp;
    }

    //用户注册
    @PostMapping("user/register")
    public ResultData<Integer> userRegister(User user){
        ResultData<Integer> resp = new ResultData<>();
        User objUser = userService.userExist(user.gettUsername());
        if(objUser != null){
            resp.error("该用户已经注册了");
        }else{
            userService.userRegister(user.gettUsername(),user.gettPassword());
            resp.ok();
        }
        return resp;

    }





    //验证码刷新
    @GetMapping("/captcha")
    public void happyCaptcha(HttpServletRequest request, HttpServletResponse response){
        HappyCaptcha.require(request,response).build().finish();
    }

}
